﻿using System;
using System.Collections.Generic;
using System.Text;
using EmbeddedSharp;
using EmbeddedSharp.Core;

namespace EmbeddedSharp.Core.Function.String {

    /// <summary>
    /// Return the index of the specific pattern in the string.
    /// 
    /// Syntax: <i>seek(expr, pattern);</i>
    /// 
    /// <b>Example</b>:
    /// idx = seek("Hello, World", "Wor"); # 
    /// </summary>
    public class SeekNode : FuncNode {

        public SeekNode()
            : base() {
            base.Value = "seek";
        }

        public override object Evaluate() {
            int length = Parameters.Count;
            if (length < 2) {
                throw new ArgumentException(
                    "Usage: seek(source, pattern)");
            }

            string expr = Parameters[length - 1].Evaluate().ToString();
            string idx = Parameters[length - 2].Evaluate().ToString();
            if (length > 2) {
                int offset = Convert.ToInt32(
                    Parameters[length - 3].Evaluate());
                return expr.IndexOf(idx, offset);
            }

            return expr.IndexOf(idx);
        }
    }
}
